<template>
  <div class="all-coffees">

    <section class="hero">
      <h1>全部咖啡豆</h1>
      <p>探索来自全国精品产区的咖啡豆</p>
    </section>

    <!-- 面包屑 -->
    <div class="container">
      <div class="breadcrumb">
        <router-link to="/">首页</router-link>
        <span class="sep">›</span>
        <span>全部咖啡豆</span>
      </div>

      <div class="layout">

        <!-- 右侧列表 -->
        <section class="products">
          <div class="toolbar">
            <div class="sort">
              <span>排序方式:</span>
              <select v-model="sortBy" @change="handleSortChange">
                <option value="recommend">推荐商品</option>
                <option value="price_asc">价格从低到高</option>
                <option value="price_desc">价格从高到低</option>
                <option value="created_at_desc">最新上架</option>
              </select>
            </div>

            <div class="view">
              <span>显示方式:</span>
              <button :class="{active:view==='grid'}" @click="view='grid'">
                <i class="fa fa-th-large"/>
              </button>
              <button :class="{active:view==='list'}" @click="view='list'">
                <i class="fa fa-list"/>
              </button>
            </div>
          </div>

          <div class="grid">
            <div v-for="item in coffees" :key="item.id" class="product-card">
                <!-- 图片区域：包含角标、收藏按钮、图片 -->
                <div class="card-image">
                  <img
                      :src="item.image_urls && item.image_urls.length > 0
          ? (item.image_urls[0].startsWith('http') ? item.image_urls[0] : `http://127.0.0.1:8000/static/${item.image_urls[0]}`)
          : ''"
                      :alt="item.name"
                  />
                  <!-- 右上角收藏按钮 -->
                  <button class="wish" @click="addTofavorite(item)"><i class="fa fa-heart-o"></i></button>
                </div>
                <!-- 信息区域：名称、描述、价格、购物车 -->
                <div class="card-info">
                  <router-link :to="'/productdetail?id=' + item.id">
                    <h3>{{ item.name }}</h3>
                  </router-link>
                  <p>{{ item.description }}</p>
                  <div class="price-area">
                    <span class="now-price">¥{{ item.price.toFixed(2) }}</span>
                    <span v-if="item.original_price" class="old-price">¥{{ item.original_price.toFixed(2) }}</span>
                  </div>
                  <button class="cart-btn" @click="addToCart(item)"><i class="fa fa-shopping-cart"></i></button>
                </div>

              </div>
          </div>
          <div class="pagination">
      <button
        class="pagination-btn"
        @click="prevPage"
        :disabled="currentPage === 1"
      >
        上一页
      </button>
      <button
        v-for="page in totalPages"
        :key="page"
        class="pagination-page"
        :class="{ 'active': currentPage === page }"
        @click="goToPage(page)"
      >
        {{ page }}
      </button>
      <button
        class="pagination-btn"
        @click="nextPage"
        :disabled="currentPage === totalPages"
      >
        下一页
      </button>
    </div>
        </section>
      </div>
    </div>
    <BackTop :visible="showTop" @click="toTop"/>
    <Footer/>
  </div>
</template>

<script>
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import BackTop from '@/components/BackTop.vue'
import FilterBox from '@/components/FilterBox.vue'
import CheckboxFilter from '@/components/CheckboxFilter.vue'
import FlavorTag from '@/components/FlavorTag.vue'
import CoffeeCard from '@/components/CoffeeCard.vue'
import Pagination from '@/components/Pagination.vue'
import api from '@/api/request'


export default {
  name: 'AllCoffees',
  components: {Header, Footer, BackTop, FilterBox, CheckboxFilter, FlavorTag, CoffeeCard, Pagination},
  data() {
    return {
      showTop: false,
      view: 'grid',
      coffees: [],
      sortedCoffees: [],
      currentPage: 1,       // 当前页码
      pageSize: 8,         // 每页数量
      totalPages: 1,        // 总页数
      totalItems: 0,         // 总商品数
      sortBy: 'recommend',  // 默认推荐商品
      sortField: 'created_at',  // 实际排序字段
      sortOrder: 'desc',     // 默认降序
      isSubmitting: false
    }
  },
  computed: {
    // 计算当前页附近需要显示的页码
    middlePages() {
      const pages = [];
      // 显示当前页前1页和后1页（如果存在）
      if (this.currentPage > 2) {
        pages.push(this.currentPage - 1);
      }
      if (this.currentPage !== 1 && this.currentPage !== this.totalPages) {
        pages.push(this.currentPage);
      }
      if (this.currentPage < this.totalPages - 1) {
        pages.push(this.currentPage + 1);
      }
      return pages;
    },
    // 排序选项展示文本（用于UI显示）
    sortOptions() {
      return [
        { value: 'created_at', label: '最新上架', order: 'desc' },
        { value: 'price', label: '价格从低到高', order: 'asc' },
        { value: 'price', label: '价格从高到低', order: 'desc' }
      ];
    }
  },
  created() {
    this.getCoffeeByPage();
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll)
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll)
  },
  watch: {
    // 监听排序字段和方向变化，重新获取数据
    sortField: function () {
      this.currentPage = 1; // 排序变化时重置到第一页
      this.getCoffeeByPage();
    },
    sortOrder: function () {
      this.currentPage = 1; // 排序变化时重置到第一页
      this.getCoffeeByPage();
    }
  },
  methods: {
    async addToCart(product) {

      if (this.$store.getters['user/isVisitor']) {
        this.$store.commit('user/SET_REDIRECT_PATH', this.$route.path);
        return this.$confirm(
                '您还暂未登录，无法购买商品，是否前往登录？',
                '提示',
                {confirmButtonText: '是', cancelButtonText: '否', type: 'warning'}
        ).then(() => {
          this.$router.push('/login');
        }).catch(() => {
          this.$message.info('已取消登录');
        });
      }

      try {
        await api.post('/cart', {
          product_id: product.id,
          product_type: 'coffee',
          quantity: 1
        })
        alert("已成功添加至购物车")
        window.location.reload();
      } catch (e) {
        console.error('422 错误详情：', e.response?.data);
        console.error('添加失败', e);
      }
    },
    //处理添加收藏
    async addTofavorite(product) {
      this.isSubmitting = true;
      try {
        await api.post('/favorite/add', {
          product_id: product.id,
          product_type: 'coffee',
        })
        this.$message.success("已成功添加至收藏");
      } catch (e) {
          console.error('完整错误对象:', e);
    let errorMsg = "添加收藏失败，请稍后再试"; // 默认错误提示

    if (e.response?.status === 400 || e.response?.status === 500) {
      // 尝试解析 JSON 或直接使用字符串
      try {
        const data = typeof e.response.data === "string"
          ? JSON.parse(e.response.data)
          : e.response.data;
        errorMsg = data.detail || data.error || errorMsg;
      } catch (parseError) {
        errorMsg = e.response.data || errorMsg;
      }
    }

    this.$message.warning(errorMsg);
  } finally {
    this.isSubmitting = false;
  }
  },
    // 处理排序选择变化
    handleSortChange() {
      // 根据选择的排序方式设置对应的字段和方向
      switch(this.sortBy) {
        case 'price_asc':
          this.sortField = 'price';
          this.sortOrder = 'asc';
          break;
        case 'price_desc':
          this.sortField = 'price';
          this.sortOrder = 'desc';
          break;
        case 'created_at_desc':
          this.sortField = 'created_at';
          this.sortOrder = 'desc';
          break;
        case 'sales_desc':
          // 假设销量字段为sales，需要后端支持
          this.sortField = 'sales';
          this.sortOrder = 'desc';
          break;
        case 'recommend':
        default:
          // 推荐商品使用默认排序
          this.sortField = 'created_at';
          this.sortOrder = 'desc';
      }
    },

    // 获取分页数据（带排序参数）
    async getCoffeeByPage() {
      try {
        const response = await this.$axios.get('coffeeProduct/page/', {
          params: {
            page: this.currentPage,
            limit: this.pageSize,
            sort_by: this.sortField,    // 传递排序字段
            sort_order: this.sortOrder  // 传递排序方向
          }
        });

        // 更新数据
        this.coffees = response.data.coffee_products;
        this.totalPages = response.data.pagination.total_pages;
        this.totalItems = response.data.pagination.total;

        // 同步更新当前的排序状态（从后端返回的值）
        this.sortField = response.data.pagination.sort_by;
        this.sortOrder = response.data.pagination.sort_order;

      } catch (error) {
        console.error('查询失败', error);
        this.$message.error('获取商品列表失败');
      }
    },

    goToPage(page) {
      if (page < 1 || page > this.totalPages || page === this.currentPage) return;
      this.currentPage = page;
      this.getCoffeeByPage();
    },

    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.getCoffeeByPage();
      }
    },

    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.getCoffeeByPage();
      }
    },

    handleScroll() {
      // 你的滚动处理逻辑
      this.showTop = window.scrollY > 300;
    }
  }
}



</script>

<style scoped>

/* 网格容器：控制卡片排列 */
.grid {
  display: grid;
  /* 每列最小宽度改为 320px，使卡片更宽 */
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

/* 单个卡片：整体外观 */
.product-card {
  background-color: #fff;
  border-radius: 12px; /* 卡片圆角 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); /* 轻微阴影增强层次感 */
  overflow: hidden; /* 防止内容溢出圆角 */
  display: flex;
  flex-direction: column; /* 上下结构：图片在上，信息在下 */
}

/* 图片区域：控制图片和角标布局 */
.card-image {
  position: relative; /* 为角标、收藏按钮做定位基准 */
  height: 200px; /* 固定图片高度，保持统一 */
  overflow: hidden; /* 裁剪超出的图片 */
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 图片等比填充，不拉伸 */
  transition: transform 0.3s ease; /*  hover 缩放动画 */
}

.card-image img:hover {
  transform: scale(1.05); /*  hover 时轻微放大 */
}

/* 左上角角标 */
.tag {
  position: absolute;
  top: 10px;
  left: 10px;
  background-color: #8B5A2B; /* 咖啡主题色 */
  color: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

/* 右上角收藏按钮 */
.wish {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 32px;
  height: 32px;
  border-radius: 50%; /* 圆形按钮 */
  background-color: rgba(255, 255, 255, 0.8);
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.3s;
}

.wish:hover {
  background-color: #fff;
  color: #8B5A2B; /*  hover 时变色 */
}

/* 信息区域：名称、描述、价格 */
.card-info {
  padding: 16px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  flex-grow: 1; /* 占满剩余高度 */
}

.card-info h3 {
  font-size: 18px;
  margin-bottom: 8px;
  color: #333;
}

.card-info p {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 12px;
  flex-grow: 1; /* 让描述区域占满中间空间 */
}

/* 价格区域：现价、原价 */
.price-area {
  display: flex;
  align-items: baseline;
  margin-bottom: 12px;
}

.now-price {
  font-size: 18px;
  font-weight: bold;
  color: #8B5A2B;
  margin-right: 8px;
}

.old-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through; /* 原价划线 */
}

/* 购物车按钮 */
.cart-btn {
  width: 100%;
  padding: 10px;
  background-color: #8B5A2B;
  color: #fff;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s;

}

.cart-btn:hover {
  background-color: #3E2723; /*  hover 时深色 */
}

.cart-btn i {
  margin-right: 6px;
}
.hero {
  height: 420px;
  background: url('https://picsum.photos/1600/900?random=12') center/cover;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, .4);
}

.hero::after {
  content: '';
  position: absolute;
  inset: 0;
  background: rgba(0, 0, 0, .45);
}

.hero h1 {
  font-size: 48px;
  font-weight: 700;
  margin-bottom: 12px;
  z-index: 1;
}

.hero p {
  font-size: 24px;
  max-width: 700px;
  text-align: center;
  z-index: 1;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 16px;
}

.breadcrumb {
  margin: 24px 0;
  font-size: 14px;
  color: #666;
}

.breadcrumb a {
  color: #8B5A2B;
}

.sep {
  margin: 0 8px;
}

.layout {
  display: grid;
  gap: 32px;
  grid-template-columns:1fr 3fr;
}

.filters {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.apply, .reset {
  padding: 14px;
  border-radius: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: .3s;
}

.apply {
  background: #8B5A2B;
  color: #fff;
  border: none;
}

.apply:hover {
  background: #3E2723;
}

.reset {
  background: #fff;
  border: 1px solid #ccc;
  color: #333;
}

.reset:hover {
  background: #f5f5f5;
}

.toolbar {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, .06);
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.toolbar select {
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-radius: 6px;
}

.view button {
  width: 32px;
  height: 32px;
  border: 1px solid #ccc;
  background: #fff;
  cursor: pointer;
  margin-left: 4px;
}

.view button.active {
  background: #8B5A2B;
  color: #fff;
  border-color: #8B5A2B;
}

.result-note {
  margin-bottom: 16px;
  font-size: 14px;
  color: #555;
}

.grid {
  display: grid;
  grid-template-columns:repeat(auto-fill, minmax(240px, 1fr));
  gap: 24px;
}

@media (max-width: 1024px) {
  .layout {
    grid-template-columns:1fr
  }
}

@media (max-width: 600px) {
  .hero h1 {
    font-size: 36px
  }

  .hero p {
    font-size: 18px
  }
}
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
}

.merchandise-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}
.products-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}
.product-item {
  width: 200px;
  border: 1px solid #eee;
  padding: 10px;
  border-radius: 4px;
  background-color: #fff;
  cursor: pointer;
  background-color: #fff;
}
.pagination-btn:hover,
.pagination-page:hover {
  background-color: #f5f5f5;
}
.pagination-page.active {
  background-color: #8b5a2b;
  color: #fff;
  border-color: #8b5a2b;
}
.pagination-btn:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.arrow-icon {
  font-size: 14px;
}
</style>